# -*- coding: utf-8 -*-
__author__ = 'xuliliang'
# @Time    : 2018/3/13 下午2:07
# @Author  : 'xuliliang'
# @Email   : xuliliang@u51.com
# @File    : redisapi.py
# @Software: PyCharm


import  redis
import sys
from rediscluster import StrictRedisCluster

#redis单点配置
# redis_host = '10.1.0.13'
# redis_port = '6379'
#redis集群配置
redis_nodes = [{'host': '10.247.22.146', 'port': 6380},
               {'host': '10.247.22.146', 'port': 6381},
               {'host': '10.247.22.146', 'port': 6382},
               {'host': '10.247.22.146', 'port': 6383},
               {'host': '10.247.22.146', 'port': 6384},
               {'host': '10.247.22.146', 'port': 6385},
               ]


class RedisApi(object):
    def __init__(self):
        # self.host = redis_host
        # self.port = redis_port
        self.redis_nodes = redis_nodes
    # def redis_connet(self):#action='single'表示连单点，action='cluster'表示连集群
    #     try:
    #         self.conn = redis.Redis(self.host,port=self.port)
    #         return  self.conn
    #     except Exception,e:
    #         print "Connect Error!"
    #         sys.exit(1)

    def redis_cluster_conn(self):
        try:
            redisconn = StrictRedisCluster(startup_nodes=self.redis_nodes)
            return  redisconn
        except Exception as e:
            print "Connect Error!"
            sys.exit(1)

    def get_key(self,key_name):
            r = self.redis_cluster_conn()
            return  r.get(key_name)


    def del_key(self,key_name):
        r = self.redis_cluster_conn()
        return r.delete(key_name)

    def set_key(self,k,n):
        r = self.redis_cluster_conn()
        return r.set(k,n)

# """
# hash redis
# """
    def hs_get_key(self,name,key):
        r=self.redis_cluster_conn()
        return r.hget(name,key)

    def hs_del_key(self,name,key):
        r=self.redis_cluster_conn()
        return r.hdel(name,key)

    def hs_set_key(self,key,field,val):
        r=self.redis_cluster_conn()
        return r.hset(key,field,val)
    def get_all(self,val):
        r=self.redis_cluster_conn()
        return r.hgetall(val)


def main():
    redis_api = RedisApi()
    # redis_api.hs_set_key("90","1324","abd")
    # redis_api.hs_del_key("90","1324")
    # print  redis_api.hs_get_key('90',"1324")
    # redis_api.set_key('abc', 'Hellod')
    # redis_api.get_key('foo')
    # print  redis_api.get_key('abc')
    # print redis_api.del_key('abc')

if __name__ == '__main__':
    main()




